package com.springboot.uav.interceptor;

import com.springboot.uav.util.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * Created by IntelliJ IDEA.
 * &#064;Author : Zys
 * &#064;create 2024/11/13 19:30
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    @Autowired
    private JWTUtil jwtUtil;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
         // 如果是OPTIONS请求，跳过拦截器
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 从请求头获取token
        String token = request.getHeader("Authorization");
        if (token == null || token.isEmpty()) {
            throw new RuntimeException("未登录");
        }

        // 验证token的有效性
        if (!jwtUtil.validateToken(token)) {
            throw new RuntimeException("token无效");
        }

        // 从Redis中验证token
        String username = jwtUtil.getUsernameFromToken(token);
        String redisToken = redisTemplate.opsForValue().get("token:" + username);
        if (redisToken == null || !redisToken.equals(token)) {
            throw new RuntimeException("token已失效");
        }

        return true;
    }
}
